package com.yonyou.pmclouds.outter.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.view.DisableWrap;
import com.yonyou.yht.sdk.UserCenter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/outter/nc")
public class HtmlRedirectController {

    private ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping(value="/redirect")
    @DisableWrap
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, BusinessException {

        String tenantid = request.getParameter("tenantid");
        String sysid = request.getParameter("sysid");
        String urlType= request.getParameter("urlType");
        String token = request.getParameter("token");
        String crossOrigin = request.getParameter("crossOrigin");

        String validateResult = UserCenter.getUserByLoginName(token);

        Map checkResultMap = null;
        try {
            checkResultMap = objectMapper.readValue(validateResult, Map.class);
        } catch (Exception e) {
            throw new BusinessException("网络错误请重试！");
        }

        String identify =(String)((Map) checkResultMap.get("user")).get("userId");

        if(request.getCookies() != null){
            for (Cookie cookie : request.getCookies())
            {
                if(cookie.getName().equals("yht_username"))
                {
                    if(cookie.getValue().indexOf(identify)<=0)
                    {
                        throw new BusinessException("登陆错误，请删除缓存后重试！");
                    }

                }
            }
        }



        response.addHeader("Set-Cookie", "tenantid="+tenantid+"; Path=/;");
        response.addHeader("Set-Cookie", "userId="+identify+"; Path=/;");
        response.addHeader("Set-Cookie", "sysid="+sysid+"; Path=/;");
        if(urlType.contains("?")){
            urlType = urlType+"&ts="+System.currentTimeMillis();
        }else{
            urlType = urlType+"?ts="+System.currentTimeMillis();
        }

        if(StringUtils.isNotEmpty(crossOrigin)){
            urlType=urlType+"&crossOrigin="+crossOrigin;
        }
        response.sendRedirect(urlType);
    }

}
